package server

import (
	"gitee.com/enjoy_5/integral-rpc/internal/model"
	"gitee.com/enjoy_5/integral-rpc/proto/integral"
	"gorm.io/gorm"
	"time"
)

func IntegralRecordPbToModel(in *integral.IntegralRecordInfo) *model.IntegralRecord {
	return &model.IntegralRecord{
		Model:          gorm.Model{ID: uint(in.ID), CreatedAt: time.Unix(in.CreateTime, 0)},
		IntegralNumber: in.IntegralNumber,
		Describe:       in.Describe,
		UserId:         in.UserId,
	}
}

func IntegralRecordModelToPb(in *model.IntegralRecord) *integral.IntegralRecordInfo {
	return &integral.IntegralRecordInfo{
		CreateTime:     in.CreatedAt.Unix(),
		ID:             int64(in.ID),
		IntegralNumber: in.IntegralNumber,
		Describe:       in.Describe,
		UserId:         in.UserId,
	}
}

// 创建积分记录
func CreateIntegralRecord(in *integral.IntegralRecordInfo) (*integral.IntegralRecordInfo, error) {
	toModel := IntegralRecordPbToModel(in)

	record, err := toModel.CreateIntegralRecord()
	if err != nil {
		return nil, err
	}

	return IntegralRecordModelToPb(record), nil
}

// 积分记录列表
func GetIntegralRecordInfoByUserId(userId int64) ([]*integral.IntegralRecordInfo, error) {
	m := new(model.IntegralRecord)

	list, err := m.GetIntegralRecordList(userId)
	if err != nil {
		return nil, err
	}
	var records []*integral.IntegralRecordInfo

	for _, v := range list {
		records = append(records, IntegralRecordModelToPb(v))
	}

	return records, nil
}
